//https://blog.csdn.net/zl1zl2zl3/article/details/81357146
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { getNodeByNameAndCallbackProcess } from '@/components/_utils/algorithmTools';
import {
    Row,
    Col,
    Card,
    Form,
    Input,
    Icon,
    Button,
    message,
    Divider,
    Table,
    Modal,
    Select
} from 'antd';
//import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import ProMenuCreateForm from './ProMenuCreateForm'; //新增表单
import ProMenuUpdateForm from './ProMenuUpdateForm'; //修改表单
import ProMenuViewForm  from './ProMenuViewForm'; //查看表单

import styles from './ProMenuList.less';
import {getValue} from '@/utils/globalcommon';
import {initTotalList} from '@/utils/globalcommon';
const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;
//菜单列表

class StandardTable extends PureComponent {
	
  constructor(props) {
    super(props);
    const { columns } = props;
    const needTotalList = initTotalList(columns);

    this.state = {
      selectedRowKeys: [],
      needTotalList,
    };
  }

  static getDerivedStateFromProps(nextProps) {
    // clean state
    if (nextProps.selectedRows.length === 0) {
      const needTotalList = initTotalList(nextProps.columns);
      return {
        selectedRowKeys: [],
        needTotalList,
      };
    }
    return null;
  }

  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    let { needTotalList } = this.state;
    needTotalList = needTotalList.map(item => ({
      ...item,
      total: selectedRows.reduce((sum, val) => sum + parseFloat(val[item.dataIndex], 10), 0),
    }));
    const { onSelectRow } = this.props;
    if (onSelectRow) {
      onSelectRow(selectedRows);
    }

    this.setState({ selectedRowKeys, needTotalList });
  };

  handleTableChange = (pagination, filters, sorter) => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(pagination, filters, sorter);
    }
  };

  cleanSelectedKeys = () => {
    this.handleRowSelectChange([], []);
  };

  render() {
    const { selectedRowKeys, needTotalList } = this.state;
    const { data = {}, rowKey, ...rest } = this.props;
    const { list = [], pagination } = data;

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      current:pagination? pagination.currentPage : 1,
      ...pagination,
    };

    const rowSelection = {
      selectedRowKeys,
      onChange: this.handleRowSelectChange,
      getCheckboxProps: record => ({
        disabled: record.disabled,
      }),
    };

    return (
      <div className={styles.standardTable}>
        <Table
          style={{overflow: 'auto'}}
          rowKey={rowKey || 'key'}
          rowSelection={rowSelection}
          dataSource={list}
          pagination={paginationProps}
          onChange={this.handleTableChange}
          {...rest}
          size="middle"
          scroll={{x: 'max-content'}}
        />
      </div>
    );
  }
}


/* eslint react/no-multi-comp:0 */
@connect(({ promenu, loading }) => ({
    promenu,
    loading: loading.models.promenu,
}))

@Form.create()
class ProMenuList extends PureComponent {
    state = {
        modalVisible: false,
        updateModalVisible: false,
        viewModalVisible: false,
        expandForm: false,
        selectedRows: [],
        formValues: {},
        updateFormValues: {},
        viewFormValues: {},
        
        currentPage:1,
        pageSize: 10,
        requestModelName:"promenu",
        root_parentid:'000000000000',
        addButtonVisible: 0,
        updateButtonVisible: 0,
        deleteButtonVisible: 0,
    };

    columns = [
		{
	        title: '名称',
	        dataIndex: 'text',
	        key: 'text',
       	}, 	{
	        title: '类型',
	        dataIndex: 'type',
	        key: 'type',
	        render:(text, record) => {
	        	return text == 1?(
	        			<Button  type="primary" size="small" style={{fontSize: '12px',backgroundColor:'#13ce66',border:'none'}}>菜单</Button>
	        		):
	        	(<Button type="primary" size="small" style={{fontSize: '12px',backgroundColor:'#ffc107',border:'none'}}>按钮</Button>)
	        }
        },  {
	        title: '链接',
	        dataIndex: 'href',
	        key: 'href',
       	}, {
	        title: '国际化菜单名',
	        dataIndex: 'i18n_name',
	        key: 'i18n_name',
       	}, {
	        title: '路由组件',
	        dataIndex: 'component',
	        key: 'component',
       	}, {
	        title: '状态',
	        dataIndex: 'enable',
	        key: 'enable',
		    render: (text,record) => {
		      	return text == 1? (
		      		<Button size="small" style={{fontSize: '12px',backgroundColor: "#e8f4ff",color: "#1890FF",border:'1px solid #d1e9ff'}}>可用</Button>
		      	):(
		      		<Button size="small" disabled style={{fontSize: '12px' }}>禁用</Button>
		      	)
	      	}
        },  {
    		title: '操作',
    		fixed:'right',
    		align: 'center',
    		width: 160,
        	render: (text, record) => {
	        	const { updateButtonVisible,deleteButtonVisible } = this.state;
	        	return (
		        	<Fragment>
						{/*<a onClick={() => this.handleViewModalVisible(true, record)}>查看</a>
						<Divider type="vertical" />
					    {updateButtonVisible == 1?(
					    	<span><a onClick={() => this.handleUpdateModalVisible(true, record)}>编辑</a>
					    	<Divider type="vertical" /></span>
					    	
					    ):null}
					    {deleteButtonVisible == 1?(
					    	<a onClick={() => this.handleDeleteRecord(record)}>删除</a>
					    ):null}*/}
					    
					    {updateButtonVisible == 1?(
					    	<Button  type="primary"  icon="edit" style={{marginRight: '5px'}} onClick={() => this.handleUpdateModalVisible(true, record)}></Button>
					    ):null}
					    {deleteButtonVisible == 1?(
					    	<Button  type="danger" icon="delete" onClick={() => this.handleDeleteRecord(record)}></Button>
					    ):null}
					    
				    </Fragment>
	        	);
	    	}

		},
];


componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
    	type: 'promenu/query_page_for_promenu',
    });
    dispatch({
    	type: 'promenu/get_promenutree_by_levelcode',
    	payload:{
        	parentid:this.state.root_parentid
        }
    });
    if(localStorage.getItem('auth_button') == "undefined") return false;
    const authButton = JSON.parse(localStorage.getItem('auth_button'));
    getNodeByNameAndCallbackProcess(authButton,"promenu",(item,index,arr) => {
    	if(item.children) {
    		item.children.map((item,index) => {
    			if(item.button_type == "add") {
    				this.setState({
    					addButtonVisible: 1,
    				})
    			}else if(item.button_type == "update") {
    				this.setState({
    					updateButtonVisible: 1,
    				})
    			}else if(item.button_type == "delete") {
    				this.setState({
    					deleteButtonVisible: 1,
    				})
    			}
    		})
    	}
    })
}



handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

	this.setState({
		currentPage: pagination.current,
		pageSize: pagination.pageSize,
		selectedRows: [],
	})

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
        const newObj = { ...obj };
	    newObj[key] = getValue(filtersArg[key]);
	    return newObj;
	}, {});

    const params = {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
        ...formValues,
        ...filters,
    };
    if (sorter.field) {
        params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
        type: 'promenu/query_page_for_promenu',
        payload: params,
    });
};

previewItem = id => {
    router.push(`/profile/basic/${id}`);
};

handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();

    this.setState({
    	currentPage:1,
        formValues: {},
		selectedRows: [],
    });
    dispatch({
        type: 'promenu/query_page_for_promenu',
        payload: {},
    });
};

toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
        expandForm: !expandForm,
    });
};


handleSelectRows = rows => {
    this.setState({
        selectedRows: rows,
    });
};

handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

	
    form.validateFields((err, fieldsValue) => {
        if (err) return;

	    const values = {
	        ...fieldsValue,
	        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
	    };
	
	    this.setState({
	    	currentPage:1,
			selectedRows: [],
	        formValues: values,
	    });
	
	    dispatch({
	        type: 'promenu/query_page_for_promenu',
	        payload: values,
	    });
	});
};

handleModalVisible = flag => {
    this.setState({
        modalVisible: !!flag,
    });
};

handleUpdateModalVisible = (flag, record) => {
    this.setState({
        updateModalVisible: !!flag,
        updateFormValues: record || {},
    });
};

handleViewModalVisible = (flag, record) => {
    this.setState({
        viewModalVisible: !!flag,
        viewFormValues: record || {},
    });
};

handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
        type: 'promenu/insert_for_promenu',
        payload: {
        	type: fields.type,
        	button_type: "",
        	text: fields.text,
        	href: fields.href,
        	component: fields.component,
        	hideInMenu: fields.hideInMenu,
        	i18n_name: fields.i18n_name,
        	redirect: fields.redirect,
        	parentid: fields.parentid,
        	parent_name: fields.parent_name,
        	levelcode: fields.levelcode,
        	enable: fields.enable,
        	
            recordid: fields.recordid,
            indexs: fields.indexs,
            icon: fields.icon,
            sequences: fields.sequences,
            hreftarget: fields.hreftarget,
            valid: fields.valid,
            leaf: fields.leaf,
            systemid: fields.systemid,
            isframe: fields.isframe,
            leaftype: fields.leaftype,
            cls: fields.cls,
            hideChildrenInMenu: fields.hideChildrenInMenu,
        },
        callback:(res) => {
        	if(res.success) {
    			message.success('添加成功');
        	}else {
        		message.success('添加失败');
        	}
        }
    });
	
	this.setState({
		selectedRows: [],
	})
	
    this.handleModalVisible();

};

handleUpdate = fields => {

    const { dispatch } = this.props;
    const { currentPage,pageSize } = this.state;
    
    dispatch({
        type: 'promenu/update_for_promenu',
        payload: {
            id: fields.id,
            text: fields.text,
            parentid: fields.parentid,
            parent_name: fields.parent_name,
            levelcode: fields.levelcode,
            href: fields.href,
            component: fields.component,
            i18n_name: fields.i18n_name,
            redirect: fields.redirect,
            enable: fields.enable,
            
            hideInMenu: fields.hideInMenu,
            indexs: fields.indexs,
            icon: fields.icon,
            sequences: fields.sequences,
            hreftarget: fields.hreftarget,
            valid: fields.valid,
            recordid: fields.recordid,
            leaf: fields.leaf,
            systemid: fields.systemid,
            isframe: fields.isframe,
            leaftype: fields.leaftype,
            cls: fields.cls,
            hideChildrenInMenu: fields.hideChildrenInMenu,
           	currentPage,
    		pageSize,
        },
        callback:(res) => {
        	if(res.success) {
    			message.success('修改成功');
        	}else {
        		message.success('修改失败');
        	}
        }
	});
	
    this.setState({
		selectedRows: [],
	})
    
    this.handleUpdateModalVisible();

};

handleDeleteRecord = record => {
    const { dispatch } = this.props;
    const { currentPage,pageSize } = this.state;    
    confirm({
	    title: '您确定要删除此菜单吗?',
	    okText: '确认',
	    cancelText: '取消',
	    onOk() {
	        dispatch({
		        type: 'promenu/delete_by_primarykey_for_promenu',
		        payload: {
	        		recordid: record.recordid,
	        		currentPage,
        			pageSize,
		        },
		        callback: (res) => {
		        	if(res.success) {
		    			message.success('删除成功');
		        	}else {
		        		message.success('删除失败');
		        	}
		        }
	        });
	    },
	    onCancel() {},
	});
	
	this.setState({
		selectedRows: [],
	})

};

renderSimpleForm() {
    const { form: { getFieldDecorator } } = this.props;
    return (
        <Form onSubmit={this.handleSearch} layout="inline">
	        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
				<Col md={8} sm={24}>
			        <FormItem label="菜单名称">
				        {getFieldDecorator('text')(<Input placeholder="请输入" />)}
					</FormItem>
			    </Col>
				{/*<Col md={8} sm={24}>
			        <FormItem label="菜单编号">
			        	{getFieldDecorator('id')(<Input placeholder="请输入" />)}
					</FormItem>
			    </Col>*/}
			    <Col md={8} sm={24}>
			        <FormItem label="状态">
			            {getFieldDecorator('enable')(
			                <Select placeholder="请选择" style={{ width: '100%' }}>
			                    <Option value="1">可用</Option>
			                    <Option value="0">禁用</Option>
			                </Select>
			            )}
			        </FormItem>
		        </Col>
			    <Col md={8} sm={24}>
			        <span className={styles.submitButtons}>
			        <Button type="primary" htmlType="submit">
			        查询
			        </Button>
			        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
			        重置
			        </Button>
			        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
			        展开 <Icon type="down" />
			        </a>
			        </span>
		        </Col>
	        </Row>
        </Form>
	);
}


renderAdvancedForm() {
    const {
        form: { getFieldDecorator },
    } = this.props;
    return (
        <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
			<Col md={8} sm={24}>
		        <FormItem label="菜单名称">
			        {getFieldDecorator('text')(<Input placeholder="请输入" />)}
				</FormItem>
		    </Col>
			{/*<Col md={8} sm={24}>
		        <FormItem label="菜单编号">
			        {getFieldDecorator('id')(<Input placeholder="请输入" />)}
				</FormItem>
		    </Col>*/}
		    <Col md={8} sm={24}>
		        <FormItem label="状态">
		            {getFieldDecorator('enable')(
		                <Select placeholder="请选择">
		                    <Option value="1">可用</Option>
		                    <Option value="0">禁用</Option>
		                </Select>
		            )}
		        </FormItem>
	        </Col>
	    	<Col md={8} sm={24}>
		        <span className={styles.submitButtons}>
		        <Button type="primary" htmlType="submit">
		        	查询
		        </Button>
		        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
		        	重置
		        </Button>
		        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
		        	收起 <Icon type="up" />
		        </a>
		        </span>
			</Col>
    	</Row>
    {/*<div style={{ overflow: 'hidden' }}>
<div style={{ marginBottom: 24 }}>
<Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>
        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
        收起 <Icon type="up" />
        </a>
        </div>
        </div>*/}
        </Form>
);
}

    renderForm() {
        const { expandForm } = this.state;
        return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
    }

    render() {
        const {
            promenu: { data,menu },
            loading,
        } = this.props;

        const { selectedRows, modalVisible, updateModalVisible, viewModalVisible,  updateFormValues,  viewFormValues,requestModelName,addButtonVisible  } = this.state;
        const parentMethods = {
            handleAdd: this.handleAdd,
            handleModalVisible: this.handleModalVisible,
            menu,
			requestModelName,
        };
        const updateMethods = {
            handleUpdateModalVisible: this.handleUpdateModalVisible,
            handleUpdate: this.handleUpdate,
            menu,
			requestModelName,
        };
        const viewMethods = {
            handleViewModalVisible: this.handleViewModalVisible
        };
        return (
            <PageHeaderWrapper title="菜单信息列表">
            <Card bordered={false}>
            <div className={styles.proMenutableList}>
            <div className={styles.proMenutableListForm}>{this.renderForm()}</div>
            <div className={styles.proMenutableListOperator}>
            {addButtonVisible == 1?(
            	<Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
        		新增
        		</Button>
        	):null}
    </div>
        <StandardTable
        rowKey={"recordid"}
        selectedRows={selectedRows}
        loading={loading}
        data={data}
        columns={this.columns}
        onSelectRow={this.handleSelectRows}
        onChange={this.handleStandardTableChange}
        />
        </div>
        </Card>

        <ProMenuCreateForm {...parentMethods} modalVisible={modalVisible} />

        {updateFormValues && Object.keys(updateFormValues).length ? (
            <ProMenuUpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={updateFormValues}
            />
        ) : null}

        {viewFormValues && Object.keys(viewFormValues).length ? (
            <ProMenuViewForm
            {...viewMethods}
            viewModalVisible={viewModalVisible}
            values={viewFormValues}
            />
        ) : null}

    </PageHeaderWrapper>
    );
    }
}

export default ProMenuList;
